import Log from '../default/Log';
import rpc from '@ohos.rpc';

const TAG = 'Dialog-constants';

const Constants = {
  SYSTEM_DIALOG_CONTROLLER: TAG + 'SystemDialog_Controller'
}

export enum Len {
  Width = 1,
  Height = 2
}

export class GlobalThis {
  private Constants = TAG + 'SystemDialog_Controller'

  // 获取globalThis下面
  static getLength(len: Len) {
    if (len === Len.Width) {
      return globalThis.display.width
    } else if (len === Len.Height) {
      return globalThis.display.height
    }
  }

  // 获取volumeDialogText
  static getText() {
    return globalThis.volumeDialogText
  }

  static onOK(connectId: string) {
    const TAG = 'Dialog-constants';

    const Constants = {
      SYSTEM_DIALOG_CONTROLLER: TAG + 'SystemDialog_Controller'
    }

    const controller = globalThis[Constants.SYSTEM_DIALOG_CONTROLLER];
    const { remoteObject } = controller.getData().get(connectId);
    if (remoteObject) {
      Log.showDebug(TAG, `onOk ${remoteObject}`);

      let data = rpc.MessageSequence.create();
      let reply = rpc.MessageSequence.create();
      let option = new rpc.MessageOption();
      remoteObject.sendMessageRequest(1, data, reply, option)
        .then(
          (result) => Log.showDebug(TAG, `onOk success ${JSON.stringify(result)}`),
          (error: Error) => {
            Log.showDebug(TAG, `onOk error ${JSON.stringify(error)}`);
            GlobalThis.onClose(connectId);
          }
        ).finally(() => {
        data.reclaim();
        reply.reclaim();
      });
    }
    return globalThis[Constants.SYSTEM_DIALOG_CONTROLLER]
  }

  static onClose(connectId: string) {
    Log.showDebug(TAG, `onClose start`);
    const controller = globalThis[Constants.SYSTEM_DIALOG_CONTROLLER];
    controller?.destroyWindow(connectId);
    Log.showInfo(TAG, `onClose end`);
  }
}